import os
import subprocess

def main():
    project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
    locales_dir = os.path.join(project_root, 'locales')

    print("Compiling .po files to .mo files...")

    # Iterate through each language directory in the locales folder
    for lang_dir in os.listdir(locales_dir):
        lang_path = os.path.join(locales_dir, lang_dir)
        if not os.path.isdir(lang_path):
            continue

        po_file_path = os.path.join(lang_path, 'LC_MESSAGES', 'messages.po')
        mo_file_path = os.path.join(lang_path, 'LC_MESSAGES', 'messages.mo')

        if os.path.exists(po_file_path):
            print(f"  - Compiling for language: {lang_dir}")
            
            # Babel's compile command requires the locale to be specified with an underscore.
            babel_lang_format = lang_dir.replace('-', '_')

            compile_command = [
                'pybabel', 'compile',
                '--input-file', po_file_path,
                '--output-file', mo_file_path,
                '--locale', babel_lang_format,
                '--statistics'
            ]
            
            try:
                result = subprocess.run(compile_command, check=True, capture_output=True, text=True)
                print(f"    {result.stdout.strip()}")
            except subprocess.CalledProcessError as e:
                print(f"    Error during compilation for {lang_dir}:")
                print(f"    {e.stderr}")

    print("\nCompilation finished.")

if __name__ == "__main__":
    main()